package com.blog.backend.utils;

import com.alibaba.fastjson.JSONObject;
import com.blog.backend.config.DirectExchangeConfig;
import com.blog.backend.domain.EntityCarHistory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

@Component
public class ConsumerListener {

    @Autowired
    private MongoTemplate  mongoTemplate;

    /**
     * 尽管设置了两个消费者，但是只有一个能够消费成功
     * 多次发送则轮训消费：
     * DirectReceiver消费者收到消息1  : 发送一条测试消息：direct
     * DirectReceiver消费者收到消息2  : 发送一条测试消息：direct
     * DirectReceiver消费者收到消息1  : 发送一条测试消息：direct
     * DirectReceiver消费者收到消息2  : 发送一条测试消息：direct
     *
     * 一个交换机可以绑定多个队列。如果通过路由key可以匹配到多个队列，消费的时候也只能有一个进行消费
     * @param testMessage
     */
    @RabbitHandler
    @RabbitListener(queues = DirectExchangeConfig.DIRECT_QUEUE)
    public void process(String testMessage) {
       //插入mongodb
        this.insertMongodb(testMessage);
    }

    @RabbitHandler
    @RabbitListener(queues = DirectExchangeConfig.DIRECT_QUEUE)
    public void process2(String testMessage) {
        this.insertMongodb(testMessage);
    }

    public void insertMongodb(String message){
        JSONObject jsonObject = JSONObject.parseObject(message);
        EntityCarHistory carHistory = new EntityCarHistory();
        carHistory.setId(UuidUtils.getId());
        carHistory.setDeviceNum(jsonObject.getString("clientId"));
        carHistory.setDeviceName(jsonObject.getString("clientId"));
        carHistory.setLongitude(new BigDecimal(jsonObject.getString("longitude")));
        carHistory.setLatitude(new BigDecimal(jsonObject.getString("latitude")));
        carHistory.setAngle(new BigDecimal(jsonObject.getString("altitude")));
        carHistory.setDirection(new BigDecimal(jsonObject.getString("direction")));
        carHistory.setSpeed(new BigDecimal(jsonObject.getString("speed")));
        Date deviceTime = jsonObject.getDate("deviceTime");
        Long time=deviceTime.getTime()+8*60*60*1000;
        Date date = new Date(time);
        carHistory.setDeviceTime(date);
        carHistory.setDeviceOnline("01");
        mongoTemplate.save(carHistory,"CarHistoryLog");
    }

}